
import UIKit
import JXBanner
import JXPageControl
import Kingfisher

protocol ZAntBannerDelegate: NSObjectProtocol {
    //
    func zAnt_bannerView(_ bannerView: ZAntBannerView, didSelectBanner index: Int)
}

class ZAntBannerView: UIView {
    
    var imageUrls: [String] = [] {
        didSet {
            self.ant_bannerView.reloadView()
        }
    }
    // size
    var bannerItemSize: CGSize = .zero
    // isAutoScroll
    var isAutoScroll: Bool = true
    // time
    var timeInterval: TimeInterval = 3.0
    
    weak var delegate: ZAntBannerDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .clear
        self.addSubview(self.ant_bannerView)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        self.ant_bannerView.frame = self.bounds
    }
    
    //MARK: - lazyloading
    private lazy var ant_bannerView: JXBanner = {
        let bannerView = JXBanner()
        bannerView.delegate = self
        bannerView.dataSource = self
        return bannerView
    }()
    
}

//MARK: - JXBannerDelegate, JXBannerDataSource
extension ZAntBannerView: JXBannerDelegate, JXBannerDataSource {
    
    func jxBanner(numberOfItems banner: JXBannerType) -> Int {
        return self.imageUrls.count
    }
    
    func jxBanner(_ banner: JXBannerType) -> (JXBannerCellRegister) {
        return JXBannerCellRegister(type: JXImageCollectionViewCell.self,
                                    reuseIdentifier: "JXImageCollectionViewCell")
    }
    
    func jxBanner(_ banner: JXBannerType, cellForItemAt index: Int, cell: UICollectionViewCell) -> UICollectionViewCell {
        guard let imageCell = cell as? JXImageCollectionViewCell else {
            return cell
        }
        imageCell.imageView.download(URL(string: self.imageUrls[index]), placeholder: UIImage(named: "ZAntImg_placeholder_big_imageAnt"))
        
        return imageCell
    }
    
    func jxBanner(_ banner: JXBannerType, params: JXBannerParams) -> JXBannerParams {
        return params.isAutoPlay(self.isAutoScroll)
            .timeInterval(self.timeInterval)
            .isPagingEnabled(true)
    }
    
    func jxBanner(_ banner: JXBannerType, layoutParams: JXBannerLayoutParams) -> JXBannerLayoutParams {
        return layoutParams.itemSize(self.bannerItemSize)
            .itemSpacing(0)
            .scrollDirection(.horizontal)
    }
    
    func jxBanner(pageControl banner: JXBannerType, numberOfPages: Int, coverView: UIView, builder: JXBannerPageControlBuilder) -> JXBannerPageControlBuilder {
        let pageControl = JXPageControlScale()
        pageControl.contentMode = .bottom
        pageControl.activeSize = CGSize(width: 6, height: 6)
        pageControl.inactiveSize = CGSize(width: 6, height: 6)
        pageControl.activeColor = UIColor.white
        pageControl.inactiveColor = UIColor.lightGray
        pageControl.columnSpacing = 8.Fit
        pageControl.isAnimation = true
        builder.pageControl = pageControl
        builder.layout = {
            pageControl.snp.makeConstraints { (maker) in
                maker.leading.trailing.equalTo(coverView)
                maker.bottom.equalTo(coverView.snp.bottom).offset(-10.Fit)
                maker.height.equalTo(20)
            }
        }
        return builder
    }
    
    func jxBanner(_ banner: JXBannerType, didSelectItemAt index: Int) {
        if let delegate = self.delegate {
            delegate.zAnt_bannerView(self, didSelectBanner: index)
            return
        }
    }
    
}


extension UIImageView {
    
    /// 下载图片
    /// - Parameters:
    ///   - url: 图片url
    ///   - isCornerRadiu: 是否圆角
    ///   - cornerRadii: 圆角值
    ///   - placeholder: 占位图
    ///   - completionHandler: 完成回调
    func download(_ url: URL?, placeholder: UIImage? = UIImage(named: "ZAntImg_Placeholder_Head_imageAnt"), completionHandler: ((UIImage) -> Void)? = nil) {
        assert(url != nil, "[图片下载] - [url: \(url?.absoluteString ?? "")] - [请检查图片地址]")
        layoutIfNeeded()
        self.kf.indicatorType = .custom(indicator: LogingProView())
        self.kf.setImage(with: url, placeholder: placeholder)
    }
    
    /// 下载图片
    /// - Parameters:
    ///   - urlStr: 下载地址
    ///   - complete: 完成回调
    static func downloadWith(urlStr: String, complete: ((UIImage?) -> ())? = nil) {
        if let url = urlStr.toURL {
            KingfisherManager.shared.retrieveImage(with: url) { (result) in
                switch result {
                case .success(let imgResult):
                    complete?(imgResult.image)
                case .failure(_):
                    complete?(nil)
                }
            }
        } else {
            complete?(nil)
        }
    }
    
}


class LogingProView: Indicator {
    
    let view = UIView()
    
    lazy var indicatorView: UIActivityIndicatorView = {
        let view = UIActivityIndicatorView(style: .medium)
        view.color = .white
        return view
    }()
    
    init() {
        view.addSubview(indicatorView)
        indicatorView.snp.makeConstraints { (make) in
            make.size.equalTo(CGSize(width: 90.Fit, height: 90.Fit))
            make.center.equalTo(view)
        }
    }
    
    func startAnimatingView() {
        view.isHidden = false
        if !indicatorView.isAnimating {
            indicatorView.startAnimating()
        }
    }
    
    func stopAnimatingView() {
        view.isHidden = true
        if indicatorView.isAnimating {
            indicatorView.stopAnimating()
        }
    }
}
